/*
 * 上海远境文化传媒有限公司 版权所有
 */
package controllers.api.v1.base;

import controllers.api.v1.auth.ApiAuth;
import controllers.license.LicenseChecker;
import facade.AppContext;
import facade.base.AdminUserFacade;
import facade.base.EntityLogFacade;
import facade.open.BaseJsonAPI;
import facade.open.request.UserPasswordRequest;
import facade.open.request.base.AdminUserRequest;
import facade.open.response.base.AdminUserResponse;
import helper.TextHelper;
import models.base.AdminUser;
import models.base.AdminUserRole;
import models.base.Corp;
import models.constants.DeletedStatus;
import models.enums.AvailableStatus;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.data.validation.Required;
import play.i18n.Messages;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.With;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by weiwei on 2018/02/26.
 * 用户接口.
 */
@With({ApiAuth.class, LicenseChecker.class})
public class AdminUserAPI extends BaseJsonAPI {
    public static final Integer PAGE_SIZE = 10;


    //首页
    public static void index(String key, Integer page, Integer pageSize, String field, String order) {
        Map<String, Object> searchMap = new HashMap<>();
        page = page == null ? 1 : page;
        pageSize = pageSize != null ? pageSize : PAGE_SIZE;

//        String orderBy = "createdAt desc";
//        if(!StringUtils.isEmpty(field)) {
//            if (StringUtils.isEmpty(order)) order = "asc";
//            orderBy = field+" "+order;
//        }
        //JPAExtPaginator<AdminUser> pageList = AdminUser.findByCondition(searchMap, orderBy, page, pageSize);
        //renderPaginator(pageList);

        Map<String,Object> pageMap = AdminUser.findByCondition(key,page,pageSize);
        renderJSON(pageMap);

    }


    //展示详情
    public static void show(@Valid @Required String id) {

        AdminUser adminUser = AdminUser.findOne(id);
        if (adminUser == null)
            renderWarnMessage(403, Messages.get("warn-no-exists","用户信息"));
        AdminUserResponse userResponse = AdminUserResponse.from(adminUser);
        renderData(userResponse);

    }


    public static void create() {
        AdminUserRequest userRequest = validateRequestBody("userRequest", AdminUserRequest.class);
        if (userRequest == null)
            renderWarnMessage(403, Messages.get("warn.no-exists","表单参数"));

        AdminUser adminUser = AdminUserFacade.create(userRequest);
        if(adminUser == null)
            renderFailMessage("操作失败！");
        AdminUserResponse userResponse = AdminUserResponse.from(adminUser);
        flash.put("notice", Messages.get("flash.notice.save-success"));
        renderData(userResponse);

    }

    public static void update(@Valid @Required String id) {
       // Corp corp = AppContext.currentCorp();
        AdminUserRequest userRequest = validateRequestBody("adminUser", AdminUserRequest.class);
        if (userRequest == null)
            renderWarnMessage(403, Messages.get("warn.no-exists","表单参数"));
        AdminUser adminUser = AdminUser.findOne(id);
        if (adminUser == null)
            renderWarnMessage(403, "用户信息不存在，无法修改!");
        AdminUser checkUser = AdminUser.findByMobile(userRequest.mobile,id);
        if(checkUser != null)
            renderWarnMessage(403, "手机号已被使用!");
        adminUser = AdminUserFacade.update(id, userRequest);
        flash.put("notice", Messages.get("flash.notice.update-success"));
        AdminUserResponse userResponse = AdminUserResponse.from(adminUser);
        renderData(userResponse);

    }

    public static void setPassword(@Valid @Required String id) {
        AdminUser loginUser = AppContext.currentUser();
       // Corp corp = AppContext.currentCorp();

        AdminUser adminUser = AdminUser.findOne(id);
        if (adminUser == null)
            renderWarnMessage(403, "用户信息不存在，无法重置密码!");
        adminUser.password = TextHelper.encryptPassword("abc123",adminUser.passwordSalt);
        adminUser.modifyAt = new Date();
        adminUser.modifyUserId = loginUser != null ?loginUser.getId() : null;
        adminUser.save();
        EntityLogFacade.log(adminUser.id, AppContext.currentUser(), AppContext.getClientType(), "重置密码:" + adminUser.name);
        flash.put("notice", Messages.get("flash.notice.update-success"));
        AdminUserResponse userResponse = AdminUserResponse.from(adminUser);
        renderData(userResponse);

    }

    public static void updatePassword() {
        AdminUser loginUser = AppContext.currentUser();
        UserPasswordRequest request = validateRequestBody("form", UserPasswordRequest.class);
        if (request == null)
            renderWarnMessage(403, Messages.get("warn-no-exists", "表单参数"));
        if (!TextHelper.isValidPassword(request.loginPass, loginUser.password, loginUser.passwordSalt)) {
            renderWarnMessage(403, "登录密码不正确");
        }
        loginUser.password = TextHelper.encryptPassword(request.newPass, loginUser.passwordSalt);
        loginUser.modifyAt = new Date();
        loginUser.modifyUserId = loginUser.getId();
        loginUser.save();
        renderSuccMessage("密码修改成功！");
    }

    /**
     * 更改状态
     *
     */
    public static  void  updateStatus(@Valid @Required String id,String status){
        AdminUser loginUser = AppContext.currentUser();
        AdminUser adminUser = AdminUser.findOne(id);
        if(adminUser == null){
            renderWarnMessage(403, "用户信息不存在，无法更改状态！");
        }
        if(StringUtils.isBlank(status)){
            renderWarnMessage(403, Messages.get("flash.warn.form.valid-fail"));
        }
        adminUser.status = AvailableStatus.valueOf(status);
        adminUser.modifyAt = new Date();
        adminUser.modifyUserId = loginUser != null ?loginUser.getId() : null;
        adminUser.save();
        EntityLogFacade.log(adminUser.id, AppContext.currentUser(), AppContext.getClientType(), "修改状态:" + adminUser.name);
        flash.put("notice", Messages.get("flash.notice.update-success", adminUser.name));
        renderSuccMessage("OK");
    }
    //删除
    public static void delete(@Valid @Required String id) {
        AdminUser loginUser = AppContext.currentUser();
        AdminUser adminUser = AdminUser.findOne(id);
        if (adminUser == null)
            renderWarnMessage(403, Messages.get("warn.no-exists", "用户信息"));

        adminUser.deleted = DeletedStatus.DELETED;
        adminUser.modifyAt = new Date();
        adminUser.modifyUserId = loginUser.getId();
        adminUser.save();
        AdminUserRole role = AdminUserRole.findByUserId(adminUser.getId());
        if(role != null){
            role.delete();
        }
        flash.put("notice", Messages.get("flash.notice.delete-success", "用户信息"));
        renderSuccMessage("删除成功！");
    }

    /**
     * 批量删除用户
     *
     */
    public static  void  deleteByIds(@Valid @Required String id){
        AdminUser loginUser = AppContext.currentUser();
        Logger.info("Log1000021 delete id ===="+id);
        String [] ids = id.split(",");
        for(String idStr : ids){
            AdminUser adminUser = AdminUser.findOne(idStr);
            if(adminUser != null) {
                adminUser.deleted = DeletedStatus.DELETED;
                adminUser.modifyAt = new Date();
                adminUser.modifyUserId = loginUser.getId();
                adminUser.save();
                AdminUserRole role = AdminUserRole.findByUserId(adminUser.getId());
                if (role != null) {
                    role.delete();
                }
            }
        }
        flash.put("notice", Messages.get("flash.notice.delete-success", ""));
        renderSuccMessage("OK");
    }
}
